# redis/redis_operations.py

from .redis_client import get_redis_client

def set_key(key: str, value: str, expire_time: int = None):
    """设置键值对"""
    client = get_redis_client()
    client.set(key, value)
    if expire_time:
        client.expire(key, expire_time)

def get_key(key: str):
    """获取键对应的值"""
    client = get_redis_client()
    value = client.get(key)
    if isinstance(value, bytes):
        return value.decode('utf-8')
    return value

def delete_key(key: str):
    """删除键"""
    client = get_redis_client()
    client.delete(key)

def check_key_exists(key: str):
    """检查键是否存在"""
    client = get_redis_client()
    return client.exists(key)

# 新增哈希操作函数
def set_hash_data(hash_key: str, data: dict, expire_time: int = None):
    """设置哈希数据"""
    client = get_redis_client()
    client.hset(hash_key, mapping=data)
    if expire_time:
        client.expire(hash_key, expire_time)

def get_hash_data(hash_key: str):
    """获取哈希数据"""
    client = get_redis_client()
    data = client.hgetall(hash_key)
    # 处理字节类型的数据
    if data:
        decoded_data = {}
        for k, v in data.items():
            key = k.decode('utf-8') if isinstance(k, bytes) else k
            value = v.decode('utf-8') if isinstance(v, bytes) else v
            decoded_data[key] = value
        return decoded_data
    return data

def get_hash_field(hash_key: str, field: str):
    """获取哈希中的特定字段"""
    client = get_redis_client()
    value = client.hget(hash_key, field)
    if isinstance(value, bytes):
        return value.decode('utf-8')
    return value

def delete_hash_key(hash_key: str):
    """删除哈希键"""
    client = get_redis_client()
    client.delete(hash_key)